var table;
var tableGroupMember;
$(function(){
    table=$("#group").DataTable({
        "ajax": {
            url:"../../admin/group/Get",
            type:"POST",
            error:function(XMLHttpRequest,textStatus,errorThrown){
                console.log("载入数据出错");
            }
        },
        "scrollX": 1200,
        "bProcessing": true,
        "bServerSide": true,
        "bPaginate": true,
        "bAutoWidth": true,
        "bInfo": true,//页脚信息
        "bFilter": false,//禁用搜索
        "bSort":false,//禁用排序
        "aLengthMenu": [2,5,10],
        "sPaginationType":'full_numbers',
        "columns": [
            {"data":"id"},
            {"data":"group_name"},
            { "data": "group_name" },
            { "data": "id" },
        ],
        "aoColumnDefs": [
            {
                "aTargets": [ 1 ],
                "mRender": function ( data, type, full ) {
                    return '<input type="checkbox" name="tab_group" value="'+data+'">';
                }
            },
            {
                "aTargets": [ 3 ],
                "mRender": function ( data, type, full ) {
                    return '<a onclick="editGroup(\''+full.id+'\',\''+full.group_name+'\')">修改</a>' +
                        '<a style="margin-left: 12px" onclick="delGroup(\''+full.id+'\')">删除</a>' +
                        '<a style="margin-left: 12px" onclick="Member(\''+full.group_name+'\')">成员</a>';
                }
            }

        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex) {
            $("td:first", nRow).html(iDisplayIndex + 1);
            return nRow;
        },
        "oLanguage": {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 条",
            "sZeroRecords": "没有匹配结果",
            "sInfo": " _START_ 至 _END_ 项结果，共 _TOTAL_ 项",//显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项
            "sInfoEmpty": "",//显示第 0 至 0 项结果，共 0 项
            "sInfoFiltered": "",//(由 _MAX_ 项结果过滤)
            "sInfoPostFix": "",
            "sSearch": "搜索：",
            "sUrl": "",
            "sEmptyTable": "没有数据呀!",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        },
    });
    importConfig($);
})

function Member(group_name) {
    $("#groupMemModal").modal("show")
    tableGroupMember=$("#groupMem").DataTable({
        "ajax": {
            url:"../../admin/group/restful/Get",
            type:"POST",
            data:function(d){
                d.group_name=group_name
            },
            error:function(XMLHttpRequest,textStatus,errorThrown){
                console.log("载入数据出错");
            }
        },
        "scrollX": 1000,
        "bProcessing": true,
        "bServerSide": true,
        "bPaginate": true,
        "bAutoWidth": true,
        "bInfo": true,//页脚信息
        "bFilter": false,//禁用搜索
        "bSort":false,//禁用排序
        "destroy":true,
        "aLengthMenu": [5,10],
        "sPaginationType":'full_numbers',
        "columns": [
            {"data":"id","width":"10%"},
            {"data":"group_name","width":"10%"},
            { "data": "name" ,"width":"10%"},
            { "data": "mobile" ,"width":"10%"},
            { "data": "e_mail" ,"width":"10%"},
            { "data": "wechat_num" ,"width":"10%"},
            { "data": "org_name" ,"width":"15%"},
            { "data": "department" ,"width":"15%"},
            { "data": "duty" ,"width":"10%"},
        ],
        "aoColumnDefs": [

        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex) {
            $("td:first", nRow).html(iDisplayIndex + 1);
            return nRow;
        },
        "oLanguage": {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 条",
            "sZeroRecords": "没有匹配结果",
            "sInfo": " _START_ 至 _END_ 项结果，共 _TOTAL_ 项",//显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项
            "sInfoEmpty": "",//显示第 0 至 0 项结果，共 0 项
            "sInfoFiltered": "",//(由 _MAX_ 项结果过滤)
            "sInfoPostFix": "",
            "sSearch": "搜索：",
            "sUrl": "",
            "sEmptyTable": "没有数据呀!",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        }
    });
}
//偏好使用HTML
new SMValidator('#addGroupName');

function search_group(){
    table.draw();
}

function add_group(){
    $(".modal-title").text("新增群组")
    $("#id").val("")
    $("#add_show").val("")
    $("#groupModal").modal("show")
}

function group_sub(){
    if(SMValidator.validate('#addGroupName')){
        $.ajax({
            url: "../../admin/group",
            type: "POST",
            dataType: "json",
            data: $("#addGroupName").serialize(),
            beforeSend: function () {
            },
            success: function (data) {
                if(data){
                    if(data!=-1) {
                        var msg = ""
                        if ($("#id").val()) {
                            msg = "修改成功"
                        } else {
                            msg = "新增成功"
                        }
                        Lobibox.notify('success', {
                            msg: msg,
                            sound: false
                        });
                    }
                    else{
                        Lobibox.notify('error', {
                            msg: "群组名重复",
                            sound: false
                        });
                    }
                    $("#groupModal").modal("hide")
                    table.draw();
                }else {
                    console.log(data)
                }
            }, error: function () {
            }
        });
    }
}

function editGroup(id,val){
    $(".modal-title").text("修改群组")
    $("#id").val(id)
    $("#add_show").val(val)
    $("#groupModal").modal("show")
}

function delGroup(id){
    Lobibox.confirm({
        msg: "确认要删除这条属性?",
        title:"删除属性",
        iconClass: false,
        callback: function ($this, type, ev) {
            if(type==='yes'){
                $.ajax({
                    url: "../../admin/group/"+id+"?_csrf="+$("input[name=_csrf]").val(),
                    type: "DELETE",
                    dataType: "json",
                    success: function (data) {
                        if(data){
                            table.draw();
                            Lobibox.notify('success', {
                                msg: '删除成功',
                                sound: false
                            });
                        }else {
                            Lobibox.notify('error', {
                                msg: '删除失败',
                                sound: false
                            });
                        }
                    }, error: function () {
                    }
                });
            }
        }
    });
}

function groupTab_box() {
    if($("input[value='groupTab_box']").prop("checked")){
        $("input[name='tab_group']").prop("checked",true);
    }
    else {
        $("input[name='tab_group']").prop("checked",false);
    }
}

function import_group() {
    $("#group-modal-form").modal("show");
}

function importConfig($) {
    $("#importGroupFile").ace_file_input({
        no_file:'选择文件 ...',
        btn_choose:'选择',
        btn_change:'选择',
        droppable:false,
        thumbnail:false, //| true | large
        whitelist:'xlsx|xls'
    }).on('change', function(){
        var names=$(this).data('ace_input_files')[0].name.split(".")
        if(names[names.length-1]!=="xlsx"&&names[names.length-1]!=="xls"){
            alert("只接受xlsx或xls文件")
            return
        }
    });
}

function submitGroupFile() {
    $("#groupFileForm").ajaxSubmit({
        type: 'POST',
        dataType: "json",
        url:"../../admin/group/import",
        success: function(data){
            console.log(data);
            if(data){
                Lobibox.notify('success', {
                    msg: "导入成功",
                    sound: false
                });
                window.location.reload();
            }else if(data="-1"){
                Lobibox.notify('error', {
                    msg: "导入群组有误",
                    sound: false
                });
            }else {
                Lobibox.notify('error', {
                    msg: "导入失败",
                    sound: false
                });
            }
            $("#group-modal-form").modal("hide")
        },
        error: function(XmlHttpRequest, textStatus, errorThrown){
            alert( "error");
        }
    })
}

function output_group(){
    // 判断是否至少选择一项
    var checkedNum = $("input[name='tab_group']:checked").length;
    if(checkedNum == 0) {
        alert("请选择至少一项！");
        return;
    }
// 批量选择
    var checkedList = [];
    $("input[name='tab_group']").each(function() {
        if($(this).is(':checked')){
            checkedList.push(encodeURIComponent($(this).val()));
        }
    });
    var SendData = {'groups':checkedList.toString()}
    window.location.href="../../admin/group/exportEmail.html?"+ $.param(SendData);

    $("input[name='tab_group']").prop("checked", false);

}

/**
 * @return {string}
 */
function JsonToSecurityString(SendData) {
    var eachData = {};
    eachData["_csrf"]=$("input[name=_csrf]").val();
    for(var i in SendData){
        eachData[i]=SendData[i];
    }
    var sendStr = "";
    for(var key in eachData){
        if (key=="_csrf"){
            sendStr += key + '=' + eachData[key];
        }else{
            sendStr += '&' + key + '=' + eachData[key];
        }
    }
    return sendStr;
}